package com.xw.kotlinlib.base

import com.xw.kotlinlib.network.TResp
import com.xw.kotlinlib.network.TResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException
import java.lang.Exception

open class BaseRepository {

    suspend fun <T : Any> apiCall(call: suspend () -> TResp<T>): TResp<T> {
        return call.invoke()
    }

    suspend fun <T : Any> safeApiCall(call: suspend () -> TResult<T>): TResult<T> {
        return try {
            call()
        } catch (e: Exception) {
            TResult.Error(e)
        }
    }

    suspend fun <T: Any> executeResponse(
        response: TResp<T>,
        successBlock: (suspend CoroutineScope.() -> Unit)? = null,
        errorBlock: (suspend CoroutineScope.() -> Unit)? = null
    ): TResult<T> {
        return coroutineScope {
            if (response.code == 200) {
                successBlock?.let { it() }
                TResult.Success(response.data)
            } else{
                errorBlock?.let { it() }
                TResult.Error(IOException(response.msg))
            }
        }
    }
}